package Service;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import Beans.Admin;
import Beans.Agent;
import Beans.Box;
import Beans.Branch;
import Beans.Courier;
import Beans.Goods;
import Beans.LogParcel;
import Beans.Package;
import Beans.Terminal;
import DAO.AgentDao;
import DAO.BoxDao;
import DAO.BranchDao;
import DAO.CourierDao;
import DAO.GoodsDao;
import DAO.LogParcelDao;
import DAO.MsgProblemDao;
import DAO.PackageDao;
import DAO.QueryDAO;
import DAO.SmsStatusDao;
import DAO.TerminalDao;
import Thread.AnJieRequestThread;
import Utils.CalculateDate;
import Utils.GetHelper;

public class BoxAndPackageService implements BoxAndPackageServiceInterface {
	BoxDao boxDao = new BoxDao();
	PackageDao packageDao = new PackageDao();
	LogParcelDao logParcelDao = new LogParcelDao();
	MsgProblemDao msgProblemDao = new MsgProblemDao();
	SmsStatusDao smsStatusDao = new SmsStatusDao();
	AgentDao agentDao = new AgentDao();
	BranchDao branchDao = new BranchDao();
	TerminalDao terminalDao = new TerminalDao();
	QueryDAO queryDAO = new QueryDAO();
	GoodsDao goodsDao = new GoodsDao();
	CourierDao courierDao = new CourierDao();

	@Override
	public List<Package> getUnTakenPakcages(int agentID, int branchID,
			int terminalID, int detained) {
		StringBuffer buffer = new StringBuffer();
		Timestamp timestamp = new Timestamp(CalculateDate.getDateBefore(
				new Date(), 1).getTime());
		if (agentID != -1) {
			buffer.append(" and p.terminal.branch.agent.id = " + agentID);
		}
		if (branchID != -1) {
			buffer.append(" and p.terminal.branch.branchId = " + branchID);
		}
		if (terminalID != -1) {
			buffer.append(" and p.terminal.terminalId = " + terminalID);
		}
		if (detained != 0) {
			buffer.append(" and p.detained = " + detained);
		}
		String hql = "from Package p where (p.packageStatus = 0 or p.packageStatus = 4) and p.storeTime < '"
				+ timestamp
				+ "'"
				+ buffer.toString()
				+ " order by p.storeTime desc";
		List<Package> packages = queryDAO.query(hql);
		return packages;
	}

	@Override
	public List<Agent> getAllAgent(List<Agent> agents) {
		agents = agentDao.getAllAgent();
		return agents;
	}
	
	@Override
	public List<Package> getStorePackage(int terminalID, int boxNum) {
		List<Package> packages = null;
		packages = packageDao.getPacakgeDetailsByBoxNum(terminalID, boxNum);
		return packages;
	}
	@Override
	public List<Goods> getStoreGoods(int terminalID, int boxNum) {
		List<Goods> goods = null;
		goods = goodsDao.getGoodsDetailsByBoxNum(terminalID,boxNum);
		return goods;
	}

	@Override
	public List<Branch> getBranchByAgent(int agentId) {
		List<Branch> branchs = branchDao.getBranchByAgentId(agentId);
		return branchs;
	}

	@Override
	public List<Terminal> getTerminalByBranch(int branchId) {
		List<Terminal> terminals = terminalDao
				.returnTermialByBranchID(branchId);
		return terminals;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#take(int, int, int)
	 */
	@Override
	public void take(int terminalID, int boxNum, int type,int packageID, Admin admin) {
		boxDao.changeBoxStatus(terminalID, boxNum,0, type,0,packageID);
		Package p = packageDao.setPackageTaken(terminalID, boxNum);
		String str = null;
		if (type == 0) {
			str = "【清空】了包裹";
		} else {
			str = "【远程开锁】了包裹";
		}
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), admin, str, "");
		logParcelDao.save(logParcel);
		if(p.getTerminal().getBranch().getAgent().getUpload()==1&&("韵达快递".equals(p.getBelong())||p.getBelong().contains("汇通"))){
			AnJieRequestThread rnt = new AnJieRequestThread();
			rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/updatePackage.html");
			rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
			rnt.setParcelId(String.valueOf(p.getPackageId()));
			rnt.setParcelNum(p.getParcelId());
			rnt.setParcelStatus(2);
			rnt.setGetTime(p.getGetTime().toString());
			Thread thread = new Thread(rnt);
			thread.start();
		}
	}
	@Override
	public void takeGoods(int terminalID, int boxNum, int type,int goodsID, Admin admin) {
		Goods goods = goodsDao.getGoodsById(goodsID);
		if(type==1){
			goods.setIsForcedOpen("1");
			boxDao.changeBoxStatus(terminalID, boxNum,1, type,goodsID,0);
		}else{
			goods.setIsForcedOpen("2");
			boxDao.changeBoxStatus(terminalID, boxNum,0, type,goodsID,0);
			goods.setStatus("4");
			goods.setGetTime(new Timestamp(new Date().getTime()));
		}
		goodsDao.editGoods(goods);
	}
	@Override
	public void unTakenGoods(int terminalID, int boxNum, int type) {
		Goods goods = goodsDao.resetLatestGoods(terminalID,boxNum);
		boxDao.changeBoxStatus(terminalID, boxNum,1, type,goods.getId(),0);
//		Goods goods = goodsDao.getGoodsById(goodsID);
//		goods.setIsForcedOpen("1");
//		goodsDao.editGoods(goods);
//		boxDao.changeBoxStatus(terminalID, boxNum,1, type,goodsID,0);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#unTaken(int, int, int)
	 */
	@Override
	public void unTaken(int terminalID, int boxNum, int type, Admin admin) {
		Package p = packageDao.setPackageUnTaken(terminalID, boxNum);
		boxDao.setBoxOccupation(terminalID, boxNum,0,p.getPackageId());
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), admin, "【反置位】了包裹", "");
		logParcelDao.save(logParcel);
		if(p.getTerminal().getBranch().getAgent().getUpload()==1&&("韵达快递".equals(p.getBelong())||p.getBelong().contains("汇通"))){
			AnJieRequestThread rnt = new AnJieRequestThread();
			rnt.setUrl("http://42.121.192.78:8086/ourangel-box-rpc/terminalSystem/updatePackage.html");
			rnt.setSign("c8db7d0e24e9a4ac3e42ec9c06ddc5f7");
			rnt.setParcelId(String.valueOf(p.getPackageId()));
			rnt.setParcelNum(p.getParcelId());
			rnt.setParcelStatus(0);
			rnt.setGetTime(null);
			Thread thread = new Thread(rnt);
			thread.start();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#back(int, int, int)
	 */
	@Override
	public void back(int terminalID, int boxNum, int type) {
		boxDao.setBoxAvailable(terminalID, boxNum, type);
		packageDao.setPackageBack(terminalID, boxNum);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see Service.BoxAndPackageServiceInterface#dealPackage(java.util.List,
	 * Beans.Package, int)
	 */
	@Override
	public List<Package> dealPackage(List<Package> packages, Package p,
			int packageID, Admin admin) {
		p = packageDao.getPackageDetailsByID(packageID);
		boxDao.setBoxAvailable(p.getTerminal().getTerminalId(), p.getBoxId(), 0);
		// boxDao.changeBoxStatus(p.getTerminal().getTerminalId(), p.getBoxId(),
		// 0, 0);
		packages = packageDao.dealPackage(packageID);
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), admin, "设置包裹为【已处理】", "");
		logParcelDao.save(logParcel);
		return packages;
	}

	@Override
	public void clearAllUseBox(int terminalID, int type) {
		List<Box> list = boxDao.getAllUseBoxOfTerminal(terminalID);
		for (Box box : list) {
			boxDao.setBoxAvailable(terminalID, box.getBoxNum(), type);
			packageDao.setPackageTaken(terminalID, box.getBoxNum());
		}
	}

	/**
	 * 标记包裹
	 */
	@Override
	public void signParcel(String newPhone,Package p, int packageID, Admin admin,
			int problemID, int operate, int detained, String reason,
			String comment) {
		StringBuffer temp = new StringBuffer();
		p = packageDao.getPackageDetailsByID(packageID);
		if (operate == 1) {// 清空箱格
			p.setGetTime(new Timestamp(new Date().getTime()));
			p.setPackageStatus(5);
			packageDao.editPackage(p);
//			packageDao.setPackageTaken(p.getTerminal().getTerminalId(),
//					p.getBoxId());
			boxDao.changeBoxStatus(p.getTerminal().getTerminalId(),
					p.getBoxId(), 0,2,0,p.getPackageId());
			temp.append("【清空】了包裹，并且");
		}
		if (operate == 2) {// 远程开箱
			p.setGetTime(new Timestamp(new Date().getTime()));
			p.setPackageStatus(5);
			packageDao.editPackage(p);
			boxDao.changeBoxStatus(p.getTerminal().getTerminalId(),
					p.getBoxId(), 0,1,0,p.getPackageId());
			temp.append("【远程开锁】了包裹，并且");
		}
		if (operate == 3) {// 系统补发短信
			temp.append("【重发了短信】，将"+p.getUserPhone()+"改为"+newPhone+"并且");
			p.setUserPhone(newPhone);
			packageDao.editPackage(p);
			GetHelper
			.doHttpGet("http://112.124.59.126:8080/YouBoxApi/controller?funcID=0031&endMsg=（系统补发）&parcelId="
					+ p.getPackageId());
		}
		if (operate == 4) {// 锁定箱格
			packageDao.signPackage(packageID);
			boxDao.changeBoxStatus(p.getTerminal().getTerminalId(),
					p.getBoxId(), 2, 2,0,packageID);
			temp.append("【锁定】了包裹，并且");
		}
		if (problemID == 1)
			temp.append("将包裹标记为【有空来取】");
		if (problemID == 2)
			temp.append("将包裹标记为【号码空号】");
		if (problemID == 3)
			temp.append("将包裹标记为【存错了】");
		if (problemID == 4)
			temp.append("将包裹标记为【未接电话】");
		if (problemID == 5)
			temp.append("将包裹标记为【空包】");
		if (problemID == 6)
			temp.append("将包裹标记为【退件】");
		if (problemID == 7) {
			temp.append("将包裹标记为【没收到短信】");
		}
		if (problemID == 8)
			temp.append("将包裹标记为【门没打开】");
		if (problemID == 9)
			temp.append("将包裹标记为【取件码失效】");
		if (problemID == 10)
			temp.append("将包裹标记为【系统维护中】");
		if (problemID == 11)
			temp.append("将包裹标记为【疑似丢件】");
		if (problemID == 12){
			temp.append("将包裹标记为【手机号码输错】");
			Courier courier = p.getCourier();
			courier.setErrorTimes(courier.getErrorTimes().add(new BigInteger("1")));
			courierDao.edit(courier);
		}
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), admin, temp.toString(), comment);
		logParcelDao.save(logParcel);
		p.setDetained(detained);
		packageDao.editPackage(p);// 修改滞留等级
//		if (problemID == 7) {
//			MsgProblem msgProblem = new MsgProblem(p.getUserPhone(), p
//					.getTerminal().getBranch().getSmsPlatform()
//					+ "", smsStatusDao.getByParcelID(packageID).get(0)
//					.getContent(), reason, admin.getUsername());
//			msgProblemDao.save(msgProblem);
//		}
	}

	/**
	 * 解锁包裹
	 */
	@Override
	public void unLockParcel(Package p, int packageID, Admin admin) {
		p = packageDao.getPackageDetailsByID(packageID);
		boxDao.changeBoxStatus(p.getTerminal().getTerminalId(), p.getBoxId(),
				1, 1,0,p.getPackageId());
		packageDao.unLockPackage(packageID);
		LogParcel logParcel = new LogParcel(p, new Timestamp(
				new Date().getTime()), admin, "【解锁】了包裹", "");
		logParcelDao.save(logParcel);
	}
}
